<template>
  <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
    <!-- 数据列表 -->
    <a-row
      class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden"
    >
      <!-- 查询条件 -->
      <a-row v-if="showSearchRow" class="w-full">
        <a-form
          :model="searchForm"
          label-align="left"
          layout="inline"
          size="small"
        >
          <a-form-item field="locationName" label="镇街名称">
            <a-input v-model="searchForm.locationName" placeholder="镇街名称" />
          </a-form-item>
        </a-form>
        <a-row class="w-full mt-2" justify="center">
          <a-space>
            <a-button type="primary" @click="getPageList(false)">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-button @click="getPageList(true)">
              <template #icon>
                <icon-sync />
              </template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-row>
      </a-row>

      <!-- 分割线 -->
      <a-divider v-if="showSearchRow" class="mt-2" />

      <!-- 市储备库指标统计 -->
      <a-row class="w-full mt-2 mb-2">
        <a-row :gutter="16" class="w-full">
          <a-col :span="6">
            <a-card :bordered="false" class="statistic-card">
              <template #title>
                <div class="card-title">
                  <icon-apps class="card-icon" />
                  <span>市储备库指标已购买面积</span>
                </div>
              </template>
              <div class="card-content">
                <a-statistic :precision="2" :value="reservePurchasedTotal">
                  <template #suffix>亩</template>
                </a-statistic>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card :bordered="false" class="statistic-card">
              <template #title>
                <div class="card-title">
                  <icon-check-circle class="card-icon" />
                  <span>市储备库指标已交易总面积</span>
                </div>
              </template>
              <div class="card-content">
                <a-statistic
                  :precision="2"
                  :value="reserveTradedTotal"
                  status="success"
                >
                  <template #suffix>亩</template>
                </a-statistic>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card :bordered="false" class="statistic-card">
              <template #title>
                <div class="card-title">
                  <icon-clock-circle class="card-icon" />
                  <span>市储备库指标剩余总面积</span>
                </div>
              </template>
              <div class="card-content">
                <a-statistic
                  :precision="2"
                  :value="reserveRemainingTotal"
                  status="warning"
                >
                  <template #suffix>亩</template>
                </a-statistic>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card :bordered="false" class="statistic-card">
              <template #title>
                <div class="card-title">
                  <span>市储备库指标待购买面积</span>
                </div>
              </template>
              <div class="card-content">
                <a-statistic
                  :precision="2"
                  :value="reserveToBuyTotal"
                  status="info"
                >
                  <template #suffix>亩</template>
                </a-statistic>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </a-row>

      <!-- 数据操作区 -->
      <a-row class="w-full flex justify-end">
        <a-space>
          <!-- 刷新 -->
          <a-button shape="circle" size="small" @click="getPageList(false)">
            <template #icon>
              <icon-refresh />
            </template>
          </a-button>
          <!-- 收缩/展开 -->
          <a-button
            shape="circle"
            size="small"
            @click="showSearchRow = !showSearchRow"
          >
            <template #icon>
              <icon-caret-up v-if="showSearchRow" />
              <icon-caret-down v-else />
            </template>
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据展示区 -->
      <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
          :columns="datatable.columns"
          :data="datatable.records"
          :loading="datatable.loading"
          :pagination="false"
          :scroll="{ minWidth: 600, y: '100%' }"
          class="w-[100%]"
          row-key="indexId"
          table-layout-fixed
        >
        </a-table>
      </a-row>
    </a-row>
  </a-card>
</template>

<script setup>
import { getCurrentInstance, reactive, ref } from "vue";
// import {
//   getLindiIndexStatisticsApi,
//   getPageLindiIndexListApi
// } from "~/api/lindi/lindiIndex.js";
import {
  IconApps,
  IconCheckCircle,
  IconClockCircle,
} from "@arco-design/web-vue/es/icon";

// 全局实例
const { proxy } = getCurrentInstance();
// 是否展示搜索区域
const showSearchRow = ref(true);
// 搜索参数表单
const searchForm = reactive({
  // 镇街名称
  locationName: null,
});
// 市储备库指标统计数据
const reservePurchasedTotal = ref(0);
const reserveTradedTotal = ref(0);
const reserveRemainingTotal = ref(0);
const reserveToBuyTotal = ref(0);

// 数据列表
const datatable = reactive({
  // 列配置
  columns: [
    {
      title: "镇街名称",
      dataIndex: "locationName",
      align: "center",
      width: 200,
    },
    {
      title: "已购买指标（亩）",
      dataIndex: "purchaseIndex",
      align: "center",
      width: 150,
      sortable: {
        sortDirections: ["ascend", "descend"],
      },
    },
    {
      title: "待购买指标（亩）",
      dataIndex: "toBuyIndex",
      align: "center",
      width: 150,
      sortable: {
        sortDirections: ["ascend", "descend"],
      },
    },
  ],
  // 数据
  records: [],
  // 加载状态
  loading: false,
});

// 页面加载完成后，加载数据
getPageList(false);
// 单独获取统计数据
getStatisticsData();

// 获取统计数据
function getStatisticsData() {
  // 暂时使用模拟数据，后续对接后端API
  try {
    // 模拟统计数据
    reservePurchasedTotal.value = 1500.5;
    reserveTradedTotal.value = 800.25;
    reserveRemainingTotal.value = 700.25;
    reserveToBuyTotal.value = 500.75;

    console.log("统计数据更新成功（模拟数据）");
  } catch (e) {
    console.error("更新统计数据失败:", e);
    proxy.$message.error("更新统计数据失败");
  }

  // TODO: 后续对接后端API
  // getLindiIndexStatisticsApi()
  //     .then((res) => {
  //       if (res) {
  //         try {
  //           const statsData = res.data || res;
  //           reservePurchasedTotal.value = parseFloat(statsData.purchasedTotal || 0);
  //           reserveTradedTotal.value = parseFloat(statsData.tradedTotal || 0);
  //           reserveRemainingTotal.value = parseFloat(statsData.remainingTotal || 0);
  //           reserveToBuyTotal.value = parseFloat(statsData.toBuyTotal || 0);
  //         } catch (e) {
  //           console.error('解析统计数据失败:', e, res);
  //           proxy.$message.error("解析统计数据失败");
  //         }
  //       }
  //     })
  //     .catch((error) => {
  //       console.error('获取统计数据失败:', error);
  //       proxy.$message.error("获取统计数据失败: " + error.message);
  //     });
}

// 获取页面数据
function getPageList(isReset) {
  if (isReset) {
    searchForm.locationName = null;
  }
  datatable.loading = true;

  // 使用前端模拟数据，不调用后端API
  try {
    // 模拟镇街数据
    const mockData = [
      {
        indexId: 1,
        locationName: "安海镇",
        purchaseIndex: 120.5,
        toBuyIndex: 80.25,
      },
      {
        indexId: 2,
        locationName: "陈埭镇",
        purchaseIndex: 95.3,
        toBuyIndex: 65.4,
      },
      {
        indexId: 3,
        locationName: "东石镇",
        purchaseIndex: 150.75,
        toBuyIndex: 90.6,
      },
      {
        indexId: 4,
        locationName: "金井镇",
        purchaseIndex: 88.2,
        toBuyIndex: 55.8,
      },
      {
        indexId: 5,
        locationName: "龙湖镇",
        purchaseIndex: 110.4,
        toBuyIndex: 75.3,
      },
      {
        indexId: 6,
        locationName: "磁灶镇",
        purchaseIndex: 75.6,
        toBuyIndex: 45.2,
      },
      {
        indexId: 7,
        locationName: "内坑镇",
        purchaseIndex: 98.8,
        toBuyIndex: 68.5,
      },
      {
        indexId: 8,
        locationName: "英林镇",
        purchaseIndex: 125.9,
        toBuyIndex: 85.7,
      },
      {
        indexId: 9,
        locationName: "紫帽镇",
        purchaseIndex: 67.4,
        toBuyIndex: 42.1,
      },
      {
        indexId: 10,
        locationName: "西滨镇",
        purchaseIndex: 105.2,
        toBuyIndex: 72.8,
      },
      {
        indexId: 11,
        locationName: "深沪镇",
        purchaseIndex: 82.3,
        toBuyIndex: 58.9,
      },
      {
        indexId: 12,
        locationName: "池店镇",
        purchaseIndex: 135.6,
        toBuyIndex: 92.4,
      },
      {
        indexId: 13,
        locationName: "青阳街道",
        purchaseIndex: 180.5,
        toBuyIndex: 120.3,
      },
      {
        indexId: 14,
        locationName: "梅岭街道",
        purchaseIndex: 165.8,
        toBuyIndex: 110.6,
      },
      {
        indexId: 15,
        locationName: "西园街道",
        purchaseIndex: 145.2,
        toBuyIndex: 95.8,
      },
      {
        indexId: 16,
        locationName: "罗山街道",
        purchaseIndex: 155.4,
        toBuyIndex: 105.2,
      },
      {
        indexId: 17,
        locationName: "新塘街道",
        purchaseIndex: 128.7,
        toBuyIndex: 88.4,
      },
      {
        indexId: 18,
        locationName: "灵源街道",
        purchaseIndex: 142.9,
        toBuyIndex: 98.6,
      },
      {
        indexId: 19,
        locationName: "陈埭镇",
        purchaseIndex: 115.3,
        toBuyIndex: 78.9,
      },
    ];

    // 如果查询条件不为空，则在前端进行筛选
    if (searchForm.locationName && searchForm.locationName.trim() !== "") {
      // 筛选包含查询条件的记录
      datatable.records = mockData.filter((record) => {
        return (
          record.locationName &&
          record.locationName.includes(searchForm.locationName)
        );
      });
    } else {
      // 如果查询条件为空，则显示所有数据
      datatable.records = mockData;
    }

    console.log("页面数据加载成功（模拟数据）");
  } catch (e) {
    console.error("加载页面数据失败:", e);
    proxy.$message.error("加载页面数据失败");
  } finally {
    datatable.loading = false;
  }

  // 单独获取最新统计数据
  getStatisticsData();

  // TODO: 后续对接后端API
  // getPageLindiIndexListApi({
  //   ...searchForm,
  //   pageSize: 999
  // })
  // .then((res) => {
  //   const originalRecords = res.records || [];
  //   const processedRecords = originalRecords.map(record => {
  //     const toBuyIndex = (Math.random() * 100).toFixed(2);
  //     return {
  //       ...record,
  //       toBuyIndex: toBuyIndex
  //     };
  //   });
  //
  //   if (searchForm.locationName && searchForm.locationName.trim() !== '') {
  //     datatable.records = processedRecords.filter(record => {
  //       return record.locationName && record.locationName.includes(searchForm.locationName);
  //     });
  //   } else {
  //     datatable.records = processedRecords;
  //   }
  // })
  // .finally(() => {
  //   datatable.loading = false;
  // });
}
</script>

<style scoped>
.image-container {
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 统计卡片样式 */
.statistic-card {
  height: 100%;
  transition: all 0.3s;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: var(--color-text-2);
}

.card-icon {
  margin-right: 8px;
  font-size: 18px;
}

.card-content {
  padding: 10px 0;
  display: flex;
  justify-content: center;
}
</style>
